import _thread
import json
import os
import socket
from third_parties.mfrc522 import MFRC522
import time
from machine import Pin
from .states import states
from .drivers import set_speed


def recv():
    (stat, tag_type) = rdr.request(rdr.REQIDL)
    if stat == rdr.OK:
        (stat, raw_uid) = rdr.anticoll()
        if stat == rdr.OK:
            print("New card detected")
            print("  - tag type: 0x%02x" % tag_type)
            print("  - uid	 : 0x%02x%02x%02x%02x" %
                  (raw_uid[3], raw_uid[2], raw_uid[1], raw_uid[0]))
            print("")
            # if states.speed == 0:
            # 在停车状态下，扫描到卡片时，发送UDP消息到主控端
            udp_s = states.get_udp_socket()
            # broadcast_addr = calculate_broadcast_address(lan_ip, mask)
            addr = (states.control_station_ip, 10130)  # 绑定端口号
            # 发起请求
            card_id = "0x%02x%02x%02x%02x" % (
                raw_uid[3], raw_uid[2], raw_uid[1], raw_uid[0])
            udp_s.sendto(json.dumps(
                {"name": states.configs.config["name"],
                 "role": states.configs.config['role'],
                 "ip": "xxxx",
                 "type": "ETT_CARD_FOUND",
                 "data": {"card_uuid": card_id}}), addr)
            #  暂时添加：扫描卡片后，将速度设置为0
            set_speed(0)




# ESP32S3
if os.uname().machine.find("ESP32S3") != -1:
    rdr = MFRC522(sda=5, sck=18, mosi=21, miso=19, rst=4)
# ESP32
else:
    rdr = MFRC522(sda=5, sck=18, mosi=23, miso=19, rst=4)

def rfid_loop():
    count = 0
    last_t = 0
    while 1:
        count += 1
        recv()
        time.sleep_ms(20)
        if time.time() - last_t > 1:
            last_t = time.time()

            print("calcs in this sec:", count)
            count = 0


_th = None


def start_rfid_thread():
    global _th
    _th = _thread.start_new_thread(rfid_loop, ())
